﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using ERP_RORZE_SYSTEM;
using System.Data.SqlClient;
using System.Data.Common;
using System.Data.OleDb;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Globalization;

namespace ERP_RORZE_DLL.Assembly
{
    public partial class panel_MaterialExportPlan : UserControl
    {
        private INISettings mySetting;
        private SqlConnection myConnection;

        private DataTable PlanTable;
        private DataTable MainPlanTable;
        private DataTable SubPlanTable;
        private DataTable StructureTable;
        private DataTable SumTable;
        
        private int state;

        public panel_MaterialExportPlan()
        {
            InitializeComponent();
            
            this.mySetting = new INISettings();
            this.myConnection = new SqlConnection(mySetting.SQLConnectionString);

            this.PlanTable = new DataTable();
            this.PlanTable.Columns.Add("CompID", typeof(string));
            this.PlanTable.Columns.Add("GroupID", typeof(string));
            this.PlanTable.Columns.Add("Quantity", typeof(float));

            this.MainPlanTable = new DataTable();
            this.MainPlanTable.Columns.Add("CompID", typeof(string));
            this.MainPlanTable.Columns.Add("GroupID", typeof(string));
            this.MainPlanTable.Columns.Add("Quantity", typeof(float));

            this.SubPlanTable = new DataTable();
            this.SubPlanTable.Columns.Add("CompID", typeof(string));
            this.SubPlanTable.Columns.Add("GroupID", typeof(string));
            this.SubPlanTable.Columns.Add("Quantity", typeof(float));

            this.StructureTable = new DataTable();
            this.StructureTable.Columns.Add("MaterialID", typeof(string));
            this.StructureTable.Columns.Add("Quantity", typeof(float));

            this.SumTable = new DataTable();
            this.SumTable.Columns.Add("MaterialID", typeof(string));
            this.SumTable.Columns.Add("Quantity", typeof(float));

            this.state = 0;

            this.gridF4MaterialExportPlan.DataSource = PlanTable;
            F4MaterialExportPlan.BestFitColumns();

            LoadCompList();
            LoadGroupList();            
        }

        ///////////////////////////////////
        /// Load Comp List
        ///////////////////////////////////
        private void LoadCompList()
        {
            try
            {
                myConnection.Open();
                SqlCommand sql_cmd = myConnection.CreateCommand();
                sql_cmd.CommandText = "SELECT DISTINCT RobotNo FROM [231_Kosei] ORDER BY RobotNo";
                SqlDataReader dataReader = sql_cmd.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Value = dataReader["RobotNo"].ToString().Trim();
                    item.Text = dataReader["RobotNo"].ToString().Trim();

                    this.compID.Properties.Items.Add(item);
                }
                dataReader.Close();
                sql_cmd.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot load Comp List");
            }
        }

        private void LoadGroupList()
        {
            try
            {
                myConnection.Open();
                SqlCommand sql_cmd = myConnection.CreateCommand();
                sql_cmd.CommandText = "SELECT [Group] FROM [231_Kosei] GROUP BY [Group]";
                SqlDataReader dataReader = sql_cmd.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem group = new ComboboxItem();
                    group.Value = dataReader["Group"].ToString().Trim();
                    group.Text = dataReader["Group"].ToString().Trim();

                    this.groupID.Properties.Items.Add(group);
                }
                dataReader.Close();
                sql_cmd.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot load Group List");
            }
        }

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            string err = null;
            string robot = null;
            string group = null;
            float quantity = 0;

            if (this.compID.SelectedIndex < 0)
            {
                err = "Please select Comp ID";
            }
            else
            {
                ComboboxItem item = (ComboboxItem)this.compID.SelectedItem;
                robot = item.Value.ToString();
            }

            if (string.IsNullOrEmpty(err))
            {
                if (this.groupID.SelectedIndex < 0)
                {
                    err = "Please select Group";
                }
                else
                {
                    ComboboxItem item = (ComboboxItem)this.groupID.SelectedItem;
                    group = item.Value.ToString();
                }
            }

            if (string.IsNullOrEmpty(err))
            {
                if (string.IsNullOrEmpty(this.quantityValue.Text.Trim()))
                {
                    err = "Please enter Quantity";
                }
                else
                {
                    if (float.TryParse(this.quantityValue.Text.Trim(), out quantity))
                    {
                        if (quantity <= 0)
                        {
                            err = "Quantity must be greater than 0";
                        }
                    }
                    else
                    {
                        err = "Invalid Quantity.";
                    }
                }
            }

            if (string.IsNullOrEmpty(err))
            {
                DataRow new_plan = this.PlanTable.NewRow();
                new_plan["CompID"] = robot;
                new_plan["GroupID"] = group;
                new_plan["Quantity"] = quantity;
                this.PlanTable.Rows.Add(new_plan);
            }
            else
            {
                MessageBox.Show(err);
            }

            F4MaterialExportPlan.BestFitColumns();
        }

        private void buttonCalculate_Click(object sender, EventArgs e)
        {
            switch (this.state)
            {
                case 0:                    
                    CalculateStore();
                    this.gridOrder.DataSource = null;
                    this.gridOrder.DataSource = this.SumTable;
                    Order.BestFitColumns();
                    this.gridOrder.BringToFront();
                    state = 1;
                    this.buttonCalculate.Text = "<< Back to Plan";
                    this.buttonDelete.Visible = false;
                    this.buttonClear.Visible = false;
                    break;
                case 1:                    
                    this.gridF4MaterialExportPlan.DataSource = null;
                    this.gridF4MaterialExportPlan.DataSource = this.PlanTable;
                    F4MaterialExportPlan.BestFitColumns();
                    this.gridF4MaterialExportPlan.BringToFront();
                    state = 0;
                    this.buttonCalculate.Text = ">> Calculate Order";
                    this.buttonDelete.Visible = true;
                    this.buttonClear.Visible = true;
                    break;
            }
        }

        //////////////////////////////////////////////
        /// Calculate store for Order
        /////////////////////////////////////////////
        private void CalculateStore()
        {
            this.MainPlanTable.Rows.Clear();
            this.MainPlanTable = this.PlanTable.Copy();

            this.StructureTable.Rows.Clear();
            this.SumTable.Rows.Clear();
            this.SubPlanTable.Rows.Clear();

            if (this.MainPlanTable.Rows.Count > 0)
            {                
                try
                {
                    myConnection.Open();
                    SqlCommand sql_cmd;
                    SqlDataReader dataReader;
                    while (this.MainPlanTable.Rows.Count > 0)
                    {
                        foreach (DataRow plan_row in this.MainPlanTable.Rows)
                        {
                            sql_cmd = myConnection.CreateCommand();
                            sql_cmd.CommandText = "SELECT PartNo, Quantity, [Group] FROM [231_Kosei]"
                                + " WHERE RobotNo='" + plan_row["CompID"].ToString().Trim() + "'"
                                + " AND ([Group]='" + plan_row["GroupID"].ToString() + "' OR [Group]='0')";
                            dataReader = sql_cmd.ExecuteReader();
                            while (dataReader.Read())
                            {
                                if (dataReader["Group"].ToString() != "0")
                                {
                                    DataRow structure_row = this.StructureTable.NewRow();
                                    structure_row["MaterialID"] = dataReader["PartNo"].ToString();                                    
                                    float qty = 0;
                                    float kosei_qty = 0;
                                    float.TryParse(plan_row["Quantity"].ToString().Trim(), out qty);
                                    float.TryParse(dataReader["Quantity"].ToString().Trim(), out kosei_qty);
                                    structure_row["Quantity"] = qty * kosei_qty;
                                    this.StructureTable.Rows.Add(structure_row);
                                }
                                else
                                {
                                    DataRow subplan_row = this.SubPlanTable.NewRow();
                                    subplan_row["CompID"] = dataReader["PartNo"].ToString();
                                    subplan_row["GroupID"] = plan_row["GroupID"].ToString();
                                    float qty = 0;
                                    float kosei_qty = 0;
                                    float.TryParse(plan_row["Quantity"].ToString().Trim(), out qty);
                                    float.TryParse(dataReader["Quantity"].ToString().Trim(), out kosei_qty);
                                    subplan_row["Quantity"] = qty * kosei_qty;
                                    this.SubPlanTable.Rows.Add(subplan_row);
                                }
                            }
                            dataReader.Close();
                            sql_cmd.Dispose();
                        }

                        this.MainPlanTable.Rows.Clear();
                        this.MainPlanTable = this.SubPlanTable.Copy();
                        this.SubPlanTable.Clear();                        
                    }
                    myConnection.Close();
                }
                catch (Exception ex)
                {
                    if (myConnection.State == ConnectionState.Open)
                    {
                        myConnection.Close();
                    }
                    MessageBox.Show("Structure Error: " + ex.Message);
                }
                                
                //////////////////////////////////////////
                /// Sum Structure Table
                //////////////////////////////////////////
                if (this.StructureTable.Rows.Count > 0)
                {
                    foreach (DataRow detail_row in this.StructureTable.Rows)
                    {
                        DataRow[] sum_rows = this.SumTable.Select("MaterialID='" + detail_row["MaterialID"].ToString() + "'");
                        if (sum_rows.Length > 0)
                        {
                            foreach (DataRow edit_row in sum_rows)
                            {
                                edit_row.BeginEdit();
                                float current_quantity = float.Parse(edit_row["Quantity"].ToString());
                                float add_quantity = float.Parse(detail_row["Quantity"].ToString());
                                edit_row["Quantity"] = current_quantity + add_quantity;
                                edit_row.EndEdit();
                            }
                        }
                        else
                        {
                            DataRow new_sum = SumTable.NewRow();
                            new_sum["MaterialID"] = detail_row["MaterialID"].ToString();
                            new_sum["Quantity"] = float.Parse(detail_row["Quantity"].ToString());
                            SumTable.Rows.Add(new_sum);                            
                        }
                    }
                }
            }
        }

        private void buttonClear_Click(object sender, EventArgs e)
        {
            this.PlanTable.Rows.Clear();
        }

        private void buttonDelete_Click(object sender, EventArgs e)
        {
            DataRow delete_row = F4MaterialExportPlan.GetFocusedDataRow();
            PlanTable.Rows.Remove(delete_row);
        }
    }
}
